<html>

<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/dygraph/1.0.1/dygraph-combined.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>


  <style>

    body{
        font-family:"Helvetica";
    }
    .graph {
        height: 500px;
        width: 100%;
    }

    .graphContainer {
        margin-left: 100px;
        margin-right: 100px;
    }

  </style>
</head>

<body>

<div class="selectors">
<button type="button" id="renderButton" onclick="render('data_file_paths.txt')">Look at Data</button><br>
<button type="button" id="renderButton" onclick="render('results_file_paths.txt')">Look at Results</button><br>
<input type="text", name="query", id="query", placeholder="type in query and press enter", onkeydown="render()",
size="50">
</div>

<div class="graphContainer">
</div>

<script type="text/javascript">


function getFilePaths(path){
  $.ajax({
    url: path,
    async: false,
    success: function (csvd) {
        filePaths = $.csv2Array(csvd);
    },
    dataType: "text",
});
  return filePaths
}

function createDiv(container, id){
  id = "graphdiv" + id
  var div = document.createElement("div");
  div.id = id
  div.className = "graph"
  container[0].appendChild(div)
  return div
}

// This addition was added to fix changes that appear to have been made between
// nab v1.0 and the current master in terms of the addition of a raw_score field
// to the numenta results files.  Further to this addition, all the dimensions
// have been added to the legend, apart from raw_score.  Although these cannot
// be plotted against additional and relevant y axis, as dygraph does not allow
// for more that 2 y axis and does not handle displaying dynamic y axis based on
// the data point selected.  However their addition does at least add them as
// series on the plot that can be moused over and their value are reported in
// the legend for allowing visualations of the std, reward_low_FP_rate and
// reward_low_FN_rate values.
function test_for_numenta(path) {
  var searchTerm = 'numenta'
  var indexOfFirst = path.indexOf(searchTerm);
  if (indexOfFirst !== -1)
    // nab version > v1.0 - new numenta_ and numentaTM csv format
    // timestamp,value,anomaly_score,raw_score,label,S(t)_reward_low_FP_rate,S(t)_reward_low_FN_rate,S(t)_standard
    use_visibility = [true, true, true, true, false, true, true, true];
  else
    // nab version > v1.0 - csv format
    // timestamp,value,anomaly_score,label,S(t)_reward_low_FP_rate,S(t)_reward_low_FN_rate,S(t)_standard
    use_visibility = [true, true, true, true, true, true, true];
  return use_visibility
}

function render(path) {
  filePaths = getFilePaths(path)
  if (event.keyCode != 13)
    return

  graphs = [];
  var graphDiv = document.getElementsByClassName("graphContainer");

  while(graphDiv[0].firstChild) graphDiv[0].removeChild(graphDiv[0].firstChild)

  var query = document.getElementById("query").value;
  var count = 0;

  var blockRedraw = false;

  for (var i = 0; i < filePaths.length; i++) {
    path = filePaths[i][0]
    if (path.indexOf(query) > -1) {
      use_visibility = test_for_numenta(path)
      graphs.push(
        new Dygraph(
          createDiv(graphDiv, count++),
          path,
          {
            visibility: use_visibility,
            series: {
              timestamp: {
                axis: "x1"
              },
              value: {
                axis: "y1"
              },
              anomaly_score: {
                axis: "y2"
              },
            },
            legend: "always",
            title: path,
            drawCallback: function (me, initial) {
              if (blockRedraw || initial) return;
              blockRedraw = true;
              var range = me.xAxisRange();
              var yrange = me.yAxisRange();

              for (var j = 0; j < selected.length; j++) {
                if (graphs[j] == me) continue;
                graphs[j].updateOptions({
                  dateWindow: range,
                  valueRange: yrange
                });
              }
              blockRedraw = false;
            },
            pointClickCallback: function(e, point) {
              timestamp = moment(new Date(point.xval));
              timestampString = timestamp.format("YYYY-MM-DD HH:mm:ss.SSS000");
              window.prompt("Copy to clipboard: Ctrl+C, Enter", timestampString);
            },
            underlayCallback: function(canvas, area, g) {
              var rowVal = g.getValue(0,1);
              var rowTime = g.getValue(0,0);

              var left = g.toDomCoords(rowTime, rowVal)[0];

              // probationary period
              row = Math.min(Math.round(0.15 * g.numRows()), 750);
              rowVal = g.getValue(row,1);
              rowTime = g.getValue(row,0);

              var right = g.toDomCoords(rowTime, rowVal)[0]

              canvas.fillStyle = "rgba(150, 150, 150, 1.0)";
              canvas.fillRect(left, area.y, right - left, area.h);
            }
          }
        )
      );
    }
  }
}
</script>

</body>
</html>
